package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {
    /**定义拦截器*/
    @Autowired
    private  TokenService tokenService;
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
      //从请求头中获取token
      String token = request.getHeader("authorization");
      //2.判断token是否为空,返回401


      if(StrUtil.isEmpty(token)){
          response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
          throw new RuntimeException("请先登录");
      }
      //3.解析token,解析不通过返回401
      Claims claims = tokenService.parseToken(token);
      if(ObjectUtil.isEmpty(claims)){
          response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
          throw new RuntimeException("认证失败");
      }
      //4.从token获取id,如果为空，返回401      Long userId = claims.get("userId",Long.class);
//      UserThreadLocal.set("userId");/*/
      Long userId = MapUtil.get(claims,"userId",Long.class);
      if(ObjectUtil.isEmpty(userId)){
          response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
          throw new RuntimeException("认证失败");
      }
      /*5.将用户id放入ThreadLocal*/
      UserThreadLocal.set(userId);
      //6.放行
      return true;
  }
/**视图渲染之后执行*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    UserThreadLocal.remove();
}
}
